package com.vgooo.util;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GSonTools {

	/**
	 * 获取单个对象数据
	 * 
	 * @param jsonString
	 * @param cls
	 * @return
	 */
	public static <T> T getSimpleObject(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析Json数据错误:" + jsonString) ;
		}finally{
			jsonString = null ;
		}
		return t;
	}

	/**
	 * 获取多个对象的List集合
	 * 
	 * @param jsonString
	 *            json格式的字符串
	 * @param cls
	 *            返回数据中的Object的类型
	 * @return List<T> 数据集合
	 */
	public static <T> List<T> getMoreObject(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
			}.getType());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析Json数据错误:" + jsonString) ;
		}finally{
			jsonString = null ;
		}
		return list;
	}

	/**
	 * 获取List集合中存放Map<String,Object>的复杂类型的数据
	 * 
	 * @param jsonString
	 * @return List<Map<String, Object>>格式的数据
	 */
	public static List<Map<String, Object>> getMulObjectList(String jsonString) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString,
					new TypeToken<List<Map<String, Object>>>() {
					}.getType());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析Json数据错误:" + jsonString) ;
		}finally{
			jsonString = null ;
		}
		return list;
	}

	/**
	 * 从jsonString中获取Map格式数据
	 * 
	 * @param jsonString
	 * @return Map<String,Object>
	 */
	public static Map<String, Object> getObjectMaps(String jsonString) {
		Map<String, Object> map = new HashMap<String, Object>();
		Gson gson = new Gson();
		try {
			map = gson.fromJson(jsonString,
					new TypeToken<Map<String, Object>>() {
					}.getType());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析Json数据错误:" + jsonString) ;
		}finally{
			jsonString = null ;
		}
		return map;
	}
}
